package com.ruoyi.project.manage.project.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.constant.ProjectConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.manage.approveLog.domain.ApproveLog;
import com.ruoyi.project.manage.approveLog.mapper.ApproveLogMapper;
import com.ruoyi.project.manage.item.domain.ProjectItem;
import com.ruoyi.project.manage.item.domain.StageItem;
import com.ruoyi.project.manage.item.mapper.ProjectItemMapper;
import com.ruoyi.project.manage.item.mapper.StageItemMapper;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.manage.project.mapper.ProjectMapper;
import com.ruoyi.project.manage.project.domain.Project;
import com.ruoyi.project.manage.project.service.IProjectService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目信息Service业务层处理
 * 
 * @author fangkun
 * @date 2022-03-28
 */
@Service
@Transactional
public class ProjectServiceImpl implements IProjectService 
{
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ApproveLogMapper approveLogMapper;
    @Autowired
    private StageItemMapper stageItemMapper;
    @Autowired
    private ProjectItemMapper projectItemMapper;

    /**
     * 查询项目信息
     * 
     * @param projectId 项目信息主键
     * @return 项目信息
     */
    @Override
    public Project selectProjectByProjectId(Long projectId)
    {
        return projectMapper.selectProjectByProjectId(projectId);
    }

    @Override
    public List<Project> selectProjectListByIds(String ids) {
        return projectMapper.selectProjectListByIds(Convert.toStrArray(ids));
    }

    /**
     * 查询项目信息列表
     * 
     * @param project 项目信息
     * @return 项目信息
     */
    @Override
    public List<Project> selectProjectList(Project project)
    {
        project.setStatus(UserConstants.NORMAL);

        if (StringUtils.isNotEmpty(project.getProjectLabel())) {
            project.setProjectLabelArray(project.getProjectLabel().split(","));
        }
        return projectMapper.selectProjectList(project);
    }

    @Override
    public List<Project> selectDelProjectList(Project project) {
        project.setStatus(UserConstants.EXCEPTION);

        if (StringUtils.isNotEmpty(project.getProjectLabel())) {
            project.setProjectLabelArray(project.getProjectLabel().split(","));
        }
        return projectMapper.selectProjectList(project);
    }

    /**
     * 新增项目信息
     * 
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public int insertProject(Project project)
    {
        // 判断是否为六定项目
        String projectLabel = project.getProjectLabel();
        if (StringUtils.isNotBlank(projectLabel)) {
            if (projectLabel.contains(ProjectConstants.LABEL_SIX_DONE+"")) {
                project.setIsSixDone(ProjectConstants.YES);
            } else {
                project.setIsSixDone(ProjectConstants.NO);
            }
        }
        // 项目状态设置为 未提交
        project.setProjectStatus(ProjectConstants.APPROVAL_UNSUBMIT);

        project.setStatus(UserConstants.NORMAL);
        project.setCreateTime(DateUtils.getNowDate());
        project.setCreateBy(ShiroUtils.getLoginName());
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());

        projectMapper.insertProject(project);

        return project.getProjectId().intValue();
    }

    /**
     * 修改项目信息
     * 
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public int updateProject(Project project)
    {
        // 设置项目属性
        setProjectInfo(project);
        // 项目状态设置为 未提交
        project.setProjectStatus(ProjectConstants.APPROVAL_UNSUBMIT);

        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    @Override
    public int editBasic(Project project) {
        // 设置项目属性
        setProjectInfo(project);

        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    /**
     * 设置项目属性，以下字段重新计算，或者置空操作
     * 1. 是否六定
     * 2. 资金需求设置
     * 3. 项目批次
     * 4. 项目进度
     * 5. 预计年产值
     * @param project
     */
    private void setProjectInfo(Project project) {
        String projectLabel = project.getProjectLabel();
        if (StringUtils.isNotBlank(projectLabel)) {
            // 判断是否为六定项目
            if (projectLabel.contains(ProjectConstants.LABEL_SIX_DONE+"")) {
                project.setIsSixDone(ProjectConstants.YES);
            } else {
                project.setIsSixDone(ProjectConstants.NO);
            }
            // 资金需求判断,如果不是资金需求项目，则置空 资金需求
            if (!projectLabel.contains(ProjectConstants.LABEL_FUND_DEMAND+"")) {
                project.setFundDemand(new BigDecimal(-1));
            }
            // 三个一批判断
            if (!projectLabel.contains(ProjectConstants.LABEL_THREE_ONE+"")) {
                // 如果不是，则置空批次字段，项目进度字段
                project.setProjectBatch(-1);
                project.setProjectProgress(-1);
            } else {
                // 设置项目进度
                // 1. 获取项目信息
                Project oriProject = projectMapper.selectProjectByProjectId(project.getProjectId());
                // 2. 项目进度已经设置，则不处理
                // 项目进度为空，则进入逻辑判断
                if (oriProject.getProjectProgress() == null) {
                    // 如果项目已经审核，则为签约
                    if (oriProject.getProjectStatus() == ProjectConstants.APPROVAL_AGREE) {
                        project.setProjectProgress(ProjectConstants.PROCESS_SIGN);
                    }
                    // 判断项目事项处理状态
                    ProjectItem projectItem = new ProjectItem();
                    projectItem.setProjectId(oriProject.getProjectId());
                    projectItem.setProjectItemStatus(ProjectConstants.ITEM_DONE);
                    projectItem.setStatus(ProjectConstants.YES + "");
                    List<ProjectItem> projectItems = projectItemMapper.selectProjectItemList(projectItem);

                    for (ProjectItem item : projectItems) {
                        String itemName = item.getStageItem().getItemName();
                        // 上传施工许可证，项目则进入施工阶段（代表项目开工）
                        if (StringUtils.equals(itemName, "施工许可证") && project.getProjectProgress() == null) {
                            project.setProjectProgress(ProjectConstants.PROCESS_IMPLEMENT);
                        }
                        // 如上传了验收报告，则项目进入验收阶段（代表项目结束或投产）
                        if (StringUtils.equals(itemName, "验收报告")) {
                            project.setProjectProgress(ProjectConstants.PROCESS_COMPLETED);
                        }
                    }

                }
            }
        } else {
            // 标签为空，则置空其他信息
            project.setProjectLabel("-1");
            project.setProjectBatch(-1);
            project.setProjectProgress(-1);
            project.setFundDemand(new BigDecimal(-1));
            project.setIsSixDone(ProjectConstants.NO);
        }
        // 项目类型判断,如果不是产业类，则置空 项目建成预计年产值
        if (project.getProjectType()!= null && project.getProjectType() != ProjectConstants.PROJECT_TYPE_PRODUCE) {
            project.setProjectWorthExpect(new BigDecimal(-1));
        }
    }

    @Override
    public int editOther(Project project) {
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    @Override
    public int submitProject(int projectId) {
        Project project = projectMapper.selectProjectByProjectId(Long.valueOf(projectId));

        if (project == null) {
            throw new ServiceException("指定项目不存在！");
        }

        if (ProjectConstants.APPROVAL_AGREE == project.getProjectStatus() || ProjectConstants.APPROVAL_SUBMIT == project.getProjectStatus()) {
            throw new ServiceException("指定项目已经提交！");
        }

        // 审批流转记录
        ApproveLog approveLog = new ApproveLog();
        approveLog.setEntityType(ProjectConstants.APPROVAL_TYPE_PROJECT);
        approveLog.setEntityId(project.getProjectId());
        approveLog.setApproveResult(ProjectConstants.APPROVAL_SUBMIT);
        approveLog.setRemark("发起审核");
        approveLog.setCreateTime(DateUtils.getNowDate());
        approveLog.setCreateBy("录入员:" + ShiroUtils.getSysUser().getUserName());
        approveLog.setUpdateTime(DateUtils.getNowDate());
        approveLog.setUpdateBy(ShiroUtils.getLoginName());
        approveLogMapper.insertApproveLog(approveLog);

        project.setProjectStatus(ProjectConstants.APPROVAL_SUBMIT);
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    @Override
    public int withdraw(int projectId) {
        Project project = projectMapper.selectProjectByProjectId(Long.valueOf(projectId));

        if (project == null) {
            throw new ServiceException("指定项目不存在！");
        }

        if (ProjectConstants.APPROVAL_SUBMIT != project.getProjectStatus()) {
            throw new ServiceException("指定项目状态不能撤回！");
        }

        // 审批流转记录
        ApproveLog approveLog = new ApproveLog();
        approveLog.setEntityType(ProjectConstants.APPROVAL_TYPE_PROJECT);
        approveLog.setEntityId(project.getProjectId());
        approveLog.setApproveResult(ProjectConstants.APPROVAL_UNSUBMIT);
        approveLog.setRemark("撤回");
        approveLog.setCreateTime(DateUtils.getNowDate());
        approveLog.setCreateBy("录入员:" + ShiroUtils.getSysUser().getUserName());
        approveLog.setUpdateTime(DateUtils.getNowDate());
        approveLog.setUpdateBy(ShiroUtils.getLoginName());
        approveLogMapper.insertApproveLog(approveLog);

        project.setProjectStatus(ProjectConstants.APPROVAL_UNSUBMIT);
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    @Override
    public int reject(Project project) {
        Project projectOld = projectMapper.selectProjectByProjectId(project.getProjectId());

        if (projectOld == null) {
            throw new ServiceException("指定项目不存在！");
        }

        if (ProjectConstants.APPROVAL_SUBMIT != projectOld.getProjectStatus()) {
            throw new ServiceException("指定项目不是上报状态！");
        }

        // 审批流转记录
        ApproveLog approveLog = new ApproveLog();
        approveLog.setEntityType(ProjectConstants.APPROVAL_TYPE_PROJECT);
        approveLog.setEntityId(project.getProjectId());
        approveLog.setApproveResult(ProjectConstants.APPROVAL_REJECT);
        approveLog.setRemark("驳回");
        approveLog.setApproveComment(project.getRejectReason());
        approveLog.setCreateTime(DateUtils.getNowDate());
        approveLog.setCreateBy("审核员:" + ShiroUtils.getSysUser().getUserName());
        approveLog.setUpdateTime(DateUtils.getNowDate());
        approveLog.setUpdateBy(ShiroUtils.getLoginName());
        approveLogMapper.insertApproveLog(approveLog);

        project.setProjectStatus(ProjectConstants.APPROVAL_REJECT);
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }

    @Override
    public int agree(int projectId) {
        Project project = projectMapper.selectProjectByProjectId(Long.valueOf(projectId));

        if (project == null) {
            throw new ServiceException("指定项目不存在！");
        }

        if (ProjectConstants.APPROVAL_SUBMIT != project.getProjectStatus()) {
            throw new ServiceException("指定项目状态不能入库！");
        }

        // 审批流转记录
        ApproveLog approveLog = new ApproveLog();
        approveLog.setEntityType(ProjectConstants.APPROVAL_TYPE_PROJECT);
        approveLog.setEntityId(project.getProjectId());
        approveLog.setApproveResult(ProjectConstants.APPROVAL_AGREE);
        approveLog.setRemark("审核通过");
        approveLog.setCreateTime(DateUtils.getNowDate());
        approveLog.setCreateBy("审核员:" + ShiroUtils.getSysUser().getUserName());
        approveLog.setUpdateTime(DateUtils.getNowDate());
        approveLog.setUpdateBy(ShiroUtils.getLoginName());
        approveLogMapper.insertApproveLog(approveLog);

        project.setProjectStatus(ProjectConstants.APPROVAL_AGREE);
        // 设置资金状态
        if (project.getInvestStatus() == null) {
            project.setInvestStatus(ProjectConstants.APPROVAL_UNSUBMIT);
        }
        // 设置六定状态
        if (project.getSixDoneStatus() == null) {
            project.setSixDoneStatus(ProjectConstants.APPROVAL_UNSUBMIT);
        }
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());

        // 初始化项目事项
        if (project.getProjectItemNum() == null || project.getProjectItemNum() == 0) {
            List<StageItem> stageItems = stageItemMapper.selectStageItemList(new StageItem());
            stageItems.stream().forEach(stageItem -> {
                ProjectItem param = new ProjectItem();
                param.setProjectId(project.getProjectId());
                param.setItemId(stageItem.getStageItemId());
                param.setProjectItemStatus(ProjectConstants.ITEM_UNSUBMIT);
                param.setIsClose(stageItem.getIsClose());

                param.setStatus(UserConstants.NORMAL);
                param.setCreateTime(DateUtils.getNowDate());
                param.setCreateBy(ShiroUtils.getLoginName());
                param.setUpdateTime(DateUtils.getNowDate());
                param.setUpdateBy(ShiroUtils.getLoginName());

                projectItemMapper.insertProjectItem(param);
            });
            project.setProjectItemNum(stageItems.size());
        }
        // 更新项目阶段
        if (project.getProjectStage() == null) {
            project.setProjectStage(ProjectConstants.PROJECT_INIT);
        }
        // 三个一批逻辑
        // 就是项目标签是三个一批项目，并且审核完成 设置签约
        if (project.getProjectProgress() == null && StringUtils.isNotBlank(project.getProjectLabel()) && project.getProjectLabel().contains(ProjectConstants.LABEL_THREE_ONE + "")) {
            project.setProjectProgress(ProjectConstants.PROCESS_SIGN);
        }
        return projectMapper.updateProject(project);
    }

    /**
     * 批量删除项目信息
     * 
     * @param projectIds 需要删除的项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectByProjectIds(String projectIds)
    {
        return projectMapper.deleteProjectByProjectIds(Convert.toStrArray(projectIds));
    }

    @Override
    public int restoreProjectByProjectIds(String projectIds) {
        return projectMapper.restoreProjectByProjectIds(Convert.toStrArray(projectIds));
    }

    /**
     * 删除项目信息信息
     * 
     * @param projectId 项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectByProjectId(Long projectId)
    {
        Project project = projectMapper.selectProjectByProjectId(Long.valueOf(projectId));

        if (project == null) {
            throw new ServiceException("指定项目不存在！");
        }

        if (ProjectConstants.APPROVAL_AGREE == project.getProjectStatus() || ProjectConstants.APPROVAL_SUBMIT == project.getProjectStatus()) {
            throw new ServiceException("指定项目状态不能删除！");
        }

        project.setStatus(UserConstants.EXCEPTION);
        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(ShiroUtils.getLoginName());
        return projectMapper.updateProject(project);
    }
}
